<template>
  <a-modal
    :visible="visible"
    :title="modalTitle"
    @ok="handleOk"
    @afterClose="afterClose"
    :destroyOnClose="true"
    :maskClosable="false"
    width="830px"
    @cancel="onCancel"
  >
    <a-form :wrapper-col="{ span: 14 }" v-if="!status">
      <a-form-item label="接警类别">
        <a-tree-select
          :tree-data="jqTreeData"
          v-model:value="callSummaryCodes"
          :replaceFields="{ children: 'children', title: 'name', key: 'code', value: 'code' }"
          treeNodeFilterProp="title"
          show-search
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择接警类别"
          allow-clear
        ></a-tree-select>
      </a-form-item>
      <a-form-item label="反馈类别">
        <a-tree-select
          :tree-data="fkTreeData"
          v-model:value="dealSummaryCodes"
          :replaceFields="{ children: 'children', title: 'name', key: 'code', value: 'code' }"
          treeNodeFilterProp="title"
          show-search
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择反馈类别"
          allow-clear
          multiple
        ></a-tree-select>
      </a-form-item>
    </a-form>

    <div class="set-rule-modal">
      <div class="rule-item-title">
        <span class="type-style">
          <a-select
            v-model:value="ruleData.period"
            style="width: 120px"
            :options="periodOptions"
          ></a-select>
          警情
          <a-select
            v-model:value="ruleData.type"
            style="width: 120px"
            :options="typeOptions"
          ></a-select>
          增长时，进行预警。
        </span>
      </div>
      <div class="rule-item-content">
        <!-- 红色预警 -->
        <span class="rule-item_level">
          <span class="red-style color-style">
            <img src="@/assets/yj-red.png" alt="" />
            红色预警：
          </span>
          ≥
          <a-input-number :min="0" :max="100000" v-model:value="ruleData.level1" />
          <span v-if="ruleData.type !== 'N'">%</span>
        </span>
        <!-- 橙色预警 -->
        <span class="rule-item_level">
          <span class="orange-style color-style">
            <img src="@/assets/yj-orange.png" alt="" />
            橙色预警：
          </span>
          ≥
          <a-input-number :min="0" :max="100000" v-model:value="ruleData.level2" />
          <span v-if="ruleData.type !== 'N'">%</span>
        </span>
        <!-- 黄色预警 -->
        <span class="rule-item_level">
          <span class="yellow-style color-style">
            <img src="@/assets/yj-yellow.png" alt="" />
            黄色预警：
          </span>
          ≥
          <a-input-number :min="0" :max="100000" v-model:value="ruleData.level3" />
          <span v-if="ruleData.type !== 'N'">%</span>
        </span>
        <!-- 蓝色预警 -->
        <span class="rule-item_level">
          <span class="blue-style color-style">
            <img src="@/assets/yj-blue.png" alt="" />
            蓝色预警：
          </span>
          ≥
          <a-input-number :min="0" :max="100000" v-model:value="ruleData.level4" />
          <span v-if="ruleData.type !== 'N'">%</span>
        </span>
      </div>
    </div>
    <template #footer>
      <div class="rule-err-msg" v-for="item in errMsg">
        该规则已在
        <span>{{ item.xqdwName }}</span>
        <span>{{ item.name }}</span>
        模型中存在，请重新添加
      </div>
      <div class="rule-err-msg" v-if="ruleErrMsg">{{ ruleErrMsg }}</div>
      <a-button key="back" @click="onCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, reactive, watch, computed, PropType } from 'vue';
import { ruleItemState } from '@/views/magic-cube/method-mode/set-ai-early-warning/js/typing';
import { useStore } from 'vuex';
import { cloneDeep } from 'lodash';

const errInfo = {
  0: '温馨提示：红色预警 > 橙色预警 > 黄色预警 > 蓝色预警',
  1: '温馨提示：请选择分类',
};
const validator = (a: number, b: number, c: number, d: number) => {
  return a > b && b > c && c > d;
};
export default defineComponent({
  props: {
    rule: {
      type: Object as PropType<ruleItemState>,
    },
    errMsg: {
      type: Array,
      defaule: [],
    },
    status: {
      type: Number,
      default: 0,
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['commit', 'update:visible'],
  setup(props, { emit }) {
    const store = useStore();
    const ruleData = reactive<ruleItemState>({
      modelId: '',
      ruleId: '', // 规则id
      period: 'D', // 周期（日-D，周-W，月-M）
      type: 'T', // 规则增长类型（T-同比，H-环比，N-数值）
      level1: 80, // 红色预警
      level2: 60, // 橙色预警
      level3: 40, // 黄色预警
      level4: 20, // 蓝色预警
    });
    const ruleErrMsg = ref('');

    const modalTitle = computed(() => {
      return props.status ? '编辑规则' : '新增规则';
    });
    const periodOptions = ref([
      {
        label: '每日',
        value: 'D',
      },
      {
        label: '每周',
        value: 'W',
      },
      {
        label: '每月',
        value: 'M',
      },
    ]);

    const typeOptions = ref([
      {
        label: '同比',
        value: 'T',
      },
      {
        label: '环比',
        value: 'H',
      },
      {
        label: '数值',
        value: 'N',
      },
    ]);
    const jqTreeData = ref([]);
    const fkTreeData = ref([]);
    const callSummaryCodes = ref([]);
    const dealSummaryCodes = ref([]);

    const handleOk = () => {
      if (!props.status && !callSummaryCodes.value.length && !dealSummaryCodes.value.length) {
        ruleErrMsg.value = errInfo[1];
        return false;
      }
      // 校验
      const validate = validator(
        ruleData.level1,
        ruleData.level2,
        ruleData.level3,
        ruleData.level4,
      );
      if (validate) {
        ruleErrMsg.value = '';
      } else {
        ruleErrMsg.value = errInfo[0];
        return false;
      }
      emit('commit', ruleData, props.status, {
        callSummaryCodes: callSummaryCodes.value.toString(),
        dealSummaryCodes: dealSummaryCodes.value.toString(),
      });
    };
    const onCancel = () => {
      ruleErrMsg.value = '';
      callSummaryCodes.value = [];
      dealSummaryCodes.value = [];
      emit('update:visible', false);
    };
    const afterClose = () => {
      console.log('afterClose');
    };

    onMounted(() => {
      store.dispatch(`dictionary/GET_TREE_PARAM`).then(() => {
        jqTreeData.value = cloneDeep(store.getters['dictionary/callTree']);
        fkTreeData.value = cloneDeep(store.getters['dictionary/dealTree']);
      });
    });

    watch(
      () => props.visible,
      () => {
        Object.keys(props.rule as ruleItemState).forEach(
          k => (ruleData[k] = (props.rule as ruleItemState)[k]),
        );
      },
      {
        deep: true,
      },
    );
    return {
      modalTitle,
      handleOk,
      onCancel,
      afterClose,
      periodOptions,
      typeOptions,
      ruleData,
      ruleErrMsg,
      jqTreeData,
      fkTreeData,
      callSummaryCodes,
      dealSummaryCodes,
    };
  },
});
</script>

<style scoped lang="less">
.set-rule-modal {
  .rule-item-title {
    .type-style {
      display: inline-block;
      color: #b9c4dd;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .type-style + .type-style {
      margin-left: 20px;
    }
  }
  :deep(.ant-input-number) {
    width: 65px;
  }
  .rule-item-content {
    padding-top: 15px;
    .rule-item_level {
      padding-right: 8px;
    }
    .red-style {
      color: #ff1b3f;
    }
    .orange-style {
      color: #ff6f1c;
    }
    .yellow-style {
      color: #ecd60d;
    }
    .blue-style {
      color: #1cdaff;
    }
    .color-style + .color-style {
      margin-left: 10px;
    }
  }
}
.rule-err-msg {
  float: left;
  height: 32px;
  padding: 0 15px;
  padding-right: 160px;
  color: #eb9797;
  font-weight: 400;
  font-size: 14px;
  line-height: 32px;
}
</style>
